// main.js
const { app, BrowserWindow, desktopCapturer, session } = require("electron");
const WebSocket = require("ws");
// const https = require("https");
const http = require("http");
// const fs = require("fs");
const path = require("path");
// 启动 WebSocket 信令服务器
function startWebSocketServer() {
  // 1. 读取证书和私钥
  // const options = {
  //   key: fs.readFileSync(path.join(__dirname, "server.key")), // 私钥文件路径
  //   cert: fs.readFileSync(path.join(__dirname, "server.crt")), // 证书文件路径
  // };
  // 2. 创建 HTTPS 服务器
  // const server = https.createServer(options, (req, res) => {
  //   res.writeHead(200, { "Content-Type": "text/plain" });
  //   res.end("Hello, HTTPS World!\n");
  // });

  // 创建http服务器
  const server = http.createServer();
  const wss = new WebSocket.Server({ server });

  wss.on("connection", (socket) => {
    socket.on("message", (msg) => {
      // 简单广播给所有其他连接
      wss.clients.forEach((client) => {
        if (client !== socket && client.readyState === WebSocket.OPEN) {
          client.send(msg);
        }
      });
    });
  });
  // 3. 监听端口
  server.listen(9000, () => {
    console.log("HTTP server running on ws://192.168.3.6:9000");
  });
}
app.whenReady().then(() => {
  // app.commandLine.appendSwitch("ignore-certificate-errors"); // 所有渲染进程和网络请求均跳过证书验证
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });
  startWebSocketServer();
  session.defaultSession.setDisplayMediaRequestHandler(
    (request, callback) => {
      desktopCapturer.getSources({ types: ["screen"] }).then((sources) => {
        // Grant access to the first screen found.
        callback({ video: sources[1], audio: "loopback" });
      });
      // If true, use the system picker if available.
      // Note: this is currently experimental. If the system picker
      // is available, it will be used and the media request handler
      // will not be invoked.
    },
    { useSystemPicker: true }
  );

  mainWindow.loadFile("index.html");
});
